import { ref, type Ref } from "vue";

export function useFind(displayedData: Ref<any[]>, tableRef: any): any {
  const selectedField = ref<keyof any>("name"); // 默认选择商品名称
  const searchContent = ref("");
  const foundRows = ref<any[]>([]);
  const currentIndex = ref(-1);
  let count = ref(0);
  let initKeyword = ref("");
  // 执行模糊查找
  const searchTable = () => {
    if (count.value !== 0) {
      highlightAndScrollToRow(foundRows.value[currentIndex.value], false);
    } else {
      count.value += 1;
    }
    initKeyword.value = searchContent.value.trim();
    const keyword = searchContent.value.trim();
    if (!keyword) return;

    const isChinese = /[\u4e00-\u9fa5]/.test(keyword); // 判断是否包含中文

    // 筛选匹配行，遍历每行的所有字段
    foundRows.value = displayedData.value.filter(row => {
      // 遍历每个字段
      for (const key in row) {
        if (Object.hasOwnProperty.call(row, key)) {
          const value = String(row[key]); // 获取字段值
          const comparisonValue = isChinese ? value : value.toLowerCase(); // 如果是中文不做大小写转换
          const comparisonKeyword = isChinese ? keyword : keyword.toLowerCase(); // 如果是中文不做大小写转换

          // 如果某个字段包含关键字，则认为这行匹配
          if (comparisonValue.includes(comparisonKeyword)) {
            return true;
          }
        }
      }
      return false; // 如果没有任何字段匹配，则这行不匹配
    });

    // 如果找到匹配项，则高亮第一项
    if (foundRows.value.length > 0) {
      currentIndex.value = 0;
      highlightAndScrollToRow(foundRows.value[currentIndex.value]);
    }
  };

  // 查找下一个
  const searchNext = () => {
    if (foundRows.value.length === 0) return;
    if (initKeyword.value !== searchContent.value) {
      searchTable(); //初始化
    } else {
      //清空上一个的高亮
      highlightAndScrollToRow(foundRows.value[currentIndex.value], false);
      // 获取下一个索引
      currentIndex.value = (currentIndex.value + 1) % foundRows.value.length;
      highlightAndScrollToRow(foundRows.value[currentIndex.value]);
    }
  };

  // 高亮并滚动到行
  const highlightAndScrollToRow = (row: any, color: boolean = true) => {
    const rowIndex = displayedData.value?.findIndex(r => r?.Record_ID === row?.Record_ID);

    if (rowIndex !== -1 && tableRef.value) {
      // 滚动到该行
      tableRef.value.scrollToRow(displayedData.value[rowIndex]);
      tableRef.value.setCurrentRow(displayedData.value[rowIndex]);

      // 高亮匹配的关键字
      const keyword = color ? searchContent.value.trim() : initKeyword.value;
      const highlightRow = (data: any) => {
        const regex = new RegExp(`(${keyword})`, "gi"); // 创建一个匹配关键字的正则表达式
        return data.replace(regex, `<span style="color: red;">$1</span>`);
      };
      // 取消高亮
      const notHighlightRow = (data: any) => {
        const regex = new RegExp(`<span style="color: red;">${keyword}</span>`, "gi"); // 创建一个匹配关键字的正则表达式
        return data.replace(regex, keyword);
      };

      // 遍历当前行的所有字段，进行关键字匹配并高亮
      Object.keys(row).forEach(key => {
        const cellValue = row[key] ? row[key].toString() : "";
        if (cellValue.includes(keyword)) {
          // 使用 v-html 或渲染函数在表格单元格中显示高亮部分
          row[key] = color ? highlightRow(cellValue) : notHighlightRow(cellValue);
        }
      });
    }
  };

  // 清除高亮和搜索内容
  const clearHighlight = () => {
    if (foundRows.value.length === 0) return;

    //清空上一个的高亮
    highlightAndScrollToRow(foundRows.value[currentIndex.value], false);
    searchContent.value = ""; // 清空搜索内容
    foundRows.value = []; // 清空找到的行
    currentIndex.value = -1; // 重置当前索引
  };

  return {
    selectedField,
    searchContent,
    foundRows,
    currentIndex,
    searchTable,
    searchNext,
    highlightAndScrollToRow,
    clearHighlight
  };
}
